package com.chao.service.impl;


import com.chao.dto.OrderDTO;
import com.chao.enums.ResultEnum;
import com.chao.exception.SellException;
import com.chao.service.BuyerService;
import com.chao.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 买家
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {

        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        return orderDTO;
    }

    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {

        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if (orderDTO == null) {
            log.error("取消订单 --- 查不到订单, orderId{}", orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);

    }

    private OrderDTO checkOrderOwner(String openid, String orderId) {

        OrderDTO orderDTO = orderService.findByOrderId(orderId);
        if (orderDTO == null) {

            return null;
        }
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
            log.error("查询订单--- 订单openid不一致, openid={}, orderId={}", openid, orderId);
            throw new SellException(ResultEnum.ORDER_ID_ERROR);
        }
        return  orderDTO;
    }
}
